package com.iptv.grape.net;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.iptv.grape.util.AppLog;
import com.iptv.grape.util.ToastUtil;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
interface IOk{
    void success(String json, String type);
    void error(String errorMsg,String type);
    void error(Exception error, String type);
}
public class Ok {
    private IOk response;
    private Context ctx;
    public Ok(IOk response,Context ctx){
        this.response = response;
        this.ctx = ctx;
    }


    public void get(Map<String,String> params, String url, String type){
        get(null,params,url,type);
    }

    public void get(Map<String,String> heads,Map<String,String> params, String url, String type){
        String urlStr = appendParams(url, params);
        FormBody.Builder builder= new FormBody.Builder();
        AppLog.getCurLog().net(type," : get ===> url = ",urlStr);
        Headers.Builder headBuilder  = new Headers.Builder();
        if(null!=heads && heads.size()>0) {
            StringBuilder stringBuffer =new StringBuilder();
            for (Map.Entry<String, String> entry : heads.entrySet()) {
                headBuilder.add(entry.getKey(), entry.getValue());
                stringBuffer.append(",").append(entry.getKey()).append("=").append(entry.getValue());
            }
            AppLog.getCurLog().net(type," : heads = ",stringBuffer.toString());
        }
        if(params!=null&&params.size()>0) {
            StringBuilder stringBuffer =new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
                stringBuffer.append(",").append(entry.getKey()).append("=").append(entry.getValue());
            }
            stringBuffer.deleteCharAt(0);
            AppLog.getCurLog().net(type," : params = ",stringBuffer.toString());
        }
        Request request =new Request.Builder()
                .url(url)
                .get()
                .headers(headBuilder.build())
                .build();

        Call newCall = okHttp().newCall(request);
        simpleCallback(newCall, type);
    }



    /*
     * 拼接参数
     */
    private String appendParams(String url,Map<String, String> map){
        StringBuilder urlStr = new StringBuilder();
        if (url.contains("?")) {
            urlStr.append(url).append("&");
        } else {
            urlStr.append(url).append("?");
        }
        for (Map.Entry<String,String> entry : map.entrySet()) {
            urlStr.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        urlStr.deleteCharAt(urlStr.length()-1);
        //get方式通信都需要传递uuid
        return urlStr.toString();
    }





    public void post(Map<String,String> params, String url, String type){
        post(null,params,url,type);
    }

    public void post(Map<String,String> heads,Map<String,String> params, String url, String type){
        FormBody.Builder builder= new FormBody.Builder();
        AppLog.getCurLog().net(type," : post ===> url = ",url);AppLog.getCurLog().net("type = ",type);
        Headers.Builder headBuilder  = new Headers.Builder();
        if(null!=heads && heads.size()>0) {
            StringBuilder stringBuffer =new StringBuilder();

            for (Map.Entry<String, String> entry : heads.entrySet()) {
                headBuilder.add(entry.getKey(), entry.getValue());
                stringBuffer.append(",").append(entry.getKey()).append("=").append(entry.getValue());
            }
            AppLog.getCurLog().net(type," : heads = ",stringBuffer.toString());
        }
        if(params!=null&&params.size()>0) {
            StringBuilder stringBuffer =new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
                stringBuffer.append(",").append(entry.getKey()).append("=").append(entry.getValue());
            }
            stringBuffer.deleteCharAt(0);
            AppLog.getCurLog().net(type," : params = ",stringBuffer.toString());
        }
        Request request =new Request.Builder()
                .url(url)
                .post( builder.build())
                .headers(headBuilder.build())
                .build();

        Call newCall = okHttp().newCall(request);
        simpleCallback(newCall, type);
    }




    public void json(String json,String url,String type){
        json(null,json,url,type);
    }
    public void json(Map<String,String> heads,String json, String url, String type){
        AppLog.getCurLog().net(type," : json: ===> url = ",url);
        Headers.Builder headBuilder  = new Headers.Builder();
        if(null!=heads && heads.size()>0) {
            StringBuilder stringBuffer =new StringBuilder();

            for (Map.Entry<String, String> entry : heads.entrySet()) {
                headBuilder.add(entry.getKey(), entry.getValue());
                stringBuffer.append(",").append(entry.getKey()).append("=").append(entry.getValue());
            }
            AppLog.getCurLog().net(type," : heads = ",stringBuffer.toString());
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        AppLog.getCurLog().net(type," : json = ",json);
        Request request =new Request.Builder()
                .url(url)
                .post(body)
                .headers(headBuilder.build())
                .build();

        Call newCall = okHttp().newCall(request);
        simpleCallback(newCall, type);
    }




    public OkHttpClient okHttp(){
        return getOkHttpClients(10,10);
    }

    private OkHttpClient  getOkHttpClients(long read_seconds,long connect_seconds){
        //根据源码可知道只有builder可以设置超时时间
        return new OkHttpClient.Builder()
                /*             .addInterceptor(if (BuildConfig.DEBUG) {
                                 HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
                             } else {
                                 HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.NONE)
                             })*/
                .readTimeout(read_seconds, TimeUnit.MILLISECONDS)
                .connectTimeout(connect_seconds, TimeUnit.MILLISECONDS)
                .build();
    }





    private void  simpleCallback(Call newCall,String type){
        if (!isNetworkConnected(ctx)) {
            ToastUtil.show("连接错误（无网络）");
            return;
        }
        try {
            Response rsps = newCall.execute();
            String value = rsps.body()!=null ?rsps.body().string():"";
            AppLog.getCurLog().net(type," : string = ",value);
            response.success(value,type);
        }catch (Exception e){
            response.error(e,type);
            response.error(e.getMessage(),type);
        }
    }


    /*
     * 无网络判定
     * @param context context
     * @return true:有网络
     */
    private static boolean isNetworkConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni == null) {
            return false;
        } else {
            return ni.isConnected();
        }
    }
}
